import router from './router';
import { useStore as useUserStore } from "@/store/user";
import { useStore as usePermissionStore } from "@/store/permission";
import { useStore as useTagsStore } from "@/store/tags";
import Cookies from 'js-cookie';

router.beforeEach(async (to, from, next) => {
  if (["404", "424"].includes(to.name as any)) {
    next();
    return
  }
  const userStore = useUserStore();
  const permissionStore = usePermissionStore();
  try {
    let yjCookies = null as any;
    yjCookies = JSON.parse(Cookies.get('X6MC_LOGIN_INFO') as any);
    const c_token = yjCookies?.accessToken;
    //当token不存在且当前Cookies里甬教里的token不等于登录接口时甬教里的token时
    if (!userStore.info.token || c_token !== userStore.info.yjToken) {
      const bol = await userStore.getInfo();
      if (!bol) {
        throw ('未获取用户登录信息');
      }
    }
    if (!permissionStore.state.pulled) {
      const accessRoutes = await permissionStore.GenerateRoutes();
      if (accessRoutes === false) {
        throw ('菜单拉取失败');
      }
      if (!accessRoutes || accessRoutes.length === 0) {
        permissionStore.state.pulled = true;
        next('/');
        return
      }
      accessRoutes?.forEach(x => {
        router.addRoute(x);
      })
    }
    if (!permissionStore.state.pulled) {
      next({ ...to, replace: true });
      permissionStore.state.pulled = true;
    } else {
      next();
    }
  } catch (error) {
    console.error(error)
    await userStore.logout();
    next('/404');
  }
})

router.afterEach((to) => {
  const tagsStore = useTagsStore();
  const { name, query, params, meta, matched } = to;
  if (to.meta?.type !== "-1") {
    tagsStore.addTag({
      name,
      query,
      params,
      meta,
      matched,
    });
  }
  tagsStore.tagChange(to);
  (document.title as any) = to.meta?.title;
})